'use strict';
const svgCaptcha = require("svg-captcha")
const Controller = require('egg').Controller;
const fs = require("fs");
const path = require("path");
const privateKey = "sun"
const axios = require("axios")
class loginController extends Controller {
    async getcaptcha() {
        const { ctx } = this;
        const captcha = svgCaptcha.create();
        ctx.session.captcha = captcha.text.toLocaleLowerCase();
        ctx.type = 'svg';
        ctx.body = captcha.data
    }
    async login() {
        const { ctx } = this;
        const { name, pwd, yzm } = ctx.request.body;
        var token = ctx.helper.token.sign({name,pwd},privateKey)
        const res = await ctx.service.login.postuser(name, pwd);
        const getcpt = ctx.session.captcha.toLocaleLowerCase()
        if (res) {
            if (yzm.toLocaleLowerCase() === getcpt) {
                ctx.cookies.set("token",token,{httpOnly:false});
                ctx.body = {
                    code: 200,
                    msg: "登录成功",
                    res,
                }
            } else {
                ctx.body = {
                    code: 200,
                    msg: "登录失败,验证码错误",
                }
            }
        } else {
            ctx.body = {
                code: 200,
                msg: "登录失败,用户名或密码错误",
            }
        }
    }
    //第三方登录
    async threeUser(){
        const {ctx} = this;
        const {code} = ctx.query;
        let config = ctx.app.config.gitee
        let res = await axios.post("https://gitee.com/oauth/token",{
            grant_type:"authorization_code",
            code,
            client_id:config.client_id,
            redirect_uri:config.redirect_uri,
            client_secret:config.client_secret
        })
        let access_token = res.data.access_token;
        let user = await axios.get('https://gitee.com/api/v5/user',{params:{
            access_token
        }})
        if(user.status===200){
            ctx.cookies.set('token',access_token,{httpOnly:false});
            ctx.body = {
                code:200,
                msg:"授权登录成功",
                data:user.data,
                token:access_token
            }
        }else{
            ctx.body = {
                code:401,
                msg:"授权失败，未获取到用户信息"
            }
        }

    }




    //upload
    async upload() {
        const {ctx} = this;
        const {filename,filepath} = ctx.request.files[0];
        //随机图片名称
        const imgname = "imgname"+JSON.stringify(Math.random()).slice(2)+Date.now()+filename
        const newimgfile = path.join(__dirname,"../public/"+imgname);
        // const filedata = fs.readFileSync(filepath);
        // fs.writeFileSync(newimgfile,filedata)
        try{
            await ctx.helper.uploads(newimgfile,filepath)
        }catch(error){}
        ctx.body = {
            code:200,
            msg:"图片上传成功",
            url:'http://localhost:7001/public/'+imgname
        }
    }
}

module.exports = loginController;
